<template>
  <div class="container" :style="containerStyle">
    <list class="item-list-container">
      <page-refresh v-on:refresh="onXRefresh" v-on:pullingDown="onPullingDown" :refreshing="refreshing"
                    :indicatorScale="indicatorScale"></page-refresh>
      <cell>
        <div style="margin-top: 12" ref="top"></div>
      </cell>
      <template v-if="userItemSelectionList.length" v-for="(userItemSelection, rowIdx) in userItemSelectionList">
        <header v-bind:key="rowIdx">
          <div class="user-info">
            <div class="user-info-left">
              <image :src="userItemSelection.userAvatarUrl" class="user-info-avatar"></image>
              <div class="user-info-detail">
                <text class="user-info-nickname">{{userItemSelection.userNickname}}</text>
                <text class="user-info-time-info">{{userItemSelection.timeInfo.value + userItemSelection.timeInfo.typeTitle}}前</text>
              </div>
            </div>
            <text class="item-selection-share-btn icon" v-if="iosShow" @click="showShare(userItemSelection)">&#xe608;{{userItemSelection.shareTimes}}</text>
          </div>
        </header>
        <cell v-bind:key="rowIdx">
          <div class="item-selection-panel">
            <text class="item-selection-content" v-if="userItemSelection.content">{{userItemSelection.content}}</text>
            <div class="item-selection-row" v-bind:key="itemListIdx" v-for="(itemList, itemListIdx) in grouping(userItemSelection.itemList, 3, {})">
              <div class="item-selection" v-bind="idx" v-for="(item, idx) in itemList" :style="{width: itemWidth, visibility: item.id ? 'visible': 'hidden'}"
                   @click="commissionItemClick(item)"
                   v-bind:key="item.id">
                <image :src="item.picUrl" :style="{width: itemWidth, height: itemWidth}" class="item-pic"></image>
                <div class="detail-row">
                  <div class="price">
                    <text class="price-y">¥</text>
                    <text class="price-val">{{item.price}}</text>
                  </div>
                  <text class="origin-price">¥{{item.originPrice}}</text>
                </div>
              </div>
            </div>
          </div>
        </cell>
      </template>
      <cell>
        <page-notice msg="抱歉，什么都木有找到～" :icon="sorryIcon" v-if="!userItemSelectionList.length && !hasNext"></page-notice>
      </cell>
      <page-loading-more v-on:loadingMore="onLoadingMore" :loadingMore="loadingMore"
                         :shown="hasNext"></page-loading-more>
    </list>
    <page-scrolltop :shown="pageScrollTopShown" @click="gotoTop"></page-scrolltop>
    <wxc-loading :show="loadingShow"></wxc-loading>
    <wxc-popup popup-color="#fff"
               :show="shareBarPopupShow"
               @wxcPopupOverlayClicked="shareBarPopupOverlayClick"
               pos="bottom"
               height="190">
      <div class="share-btns">
        <div class="share-btn">
          <text class="share-btn-icon btn-wx icon activeable" v-if="!iosHide" @click="share('pyq')">&#xe628;</text>
          <text class="share-btn-text">朋友圈</text>
        </div>
        <div class="share-btn">
          <text class="share-btn-icon btn-wx icon activeable" v-if="!iosHide" @click="share('wxhy')">&#xe66a;</text>
          <text class="share-btn-text">微信好友</text>
        </div>
        <div class="share-btn">
          <text class="share-btn-icon btn-img icon activeable" @click="share('img')">&#xe61d;</text>
          <text class="share-btn-text">保存图片</text>
        </div>
        <div class="share-btn">
          <text class="share-btn-icon btn-copy icon activeable" @click="copyShareText()">&#xe61f;</text>
          <text class="share-btn-text">复制文案</text>
        </div>
      </div>
    </wxc-popup>
  </div>
</template>
<style lang="scss">
  @import "../sass/var";
  @import "../sass/mixin";
  @import "../sass/buttons";
  @import "../sass/icon";

  .container {
    background-color: $body-bg;
    transition: transform .3s linear;
  }
  .item-list-container {
    /*background-color: #FFFFFF;*/
  }

  .share-btns {
    flex-direction: row;
    justify-content: space-between;
    align-items: center;
    padding: 20px;
  }

  .share-btn {
    flex: 1;
    justify-content: center;
    align-items: center;
    &-icon {
      font-size: 60px;
      color: #ffffff;
      text-align: center;
      width: 100px;
      height: 100px;
      border-radius: 100px;
      line-height: 100px;
    }
    &-text {
      color: $color;
      margin-top: 10px;
      font-size: 28px;
    }
  }

  .btn-wx {
    background-color: #1FCB28;
  }

  .btn-qq {
    background-color: #43B1E9;
  }

  .btn-img {
    background-color: #A98264;
  }

  .btn-copy {
    background-color: $brand-warning;
  }

  .user-info {
    padding: 10px;
    background-color: #FFFFFF;
    flex-direction: row;
    align-items: center;
    justify-content: space-between;
    &-left {
      flex-direction: row;
      align-items: center;
    }
    &-avatar {
      width: 80px;
      height: 80px;
      border-radius: 80px;
    }
    &-detail {
      justify-content: space-around;
      padding-left: 20px;
    }
    &-nickname {
      font-size: 28px;
      color: $color-warning;
    }
    &-time-info {
      font-size: 20px;
      color: $color-muted;
    }
  }

  .footer {
    position: fixed;
    bottom: 0;
    right: 0;
    left: 0;
    padding: 20px;
    flex-direction: row;
  }

  .item-selection {
    position: relative;
    &-panel {
      background-color: #FFFFFF;
      margin-bottom: 12px;
    }
    &-row {
      flex-direction: row;
      justify-content: space-between;
      padding: 0 10px;
      background-color: #FFFFFF;
    }
    &-content {
      padding:  10px 10px 20px 10px;
      font-weight: 300;
      font-size: 28px;
      color: $color;
      line-height: 32px;
    }
    &-share-btn {
      @include border(1, solid, $brand-primary);
      color: $color-primary;
      height: 40px;
      padding: 0 15px;
      border-radius: 40px;
      line-height: 40px;
      font-weight: 300;
      text-align: center;
      font-size: 24px;
      background-color: transparent;
      &:active {
        background-color: $color-primary;
        color: #FFFFFF;
      }
    }
  }

  .topbar {
    position: absolute;
    top: 0;
    right: 0;
    padding: 10px;
    left: 0;
    align-items: center;
    justify-content: flex-end;
    justify-items: flex-end;
    flex-direction: row;
    &-btn {
      margin-left: 10px
    }
  }

  .detail-row {
    flex-direction: row;
    justify-content: space-between;
    padding: 5px 10px;
    align-items: center;
    position: absolute;
    bottom: 5px;
    right: 5px;
    background-color: $brand-primary;
    border-bottom-left-radius: 20px;
    border-top-right-radius: 20px;
  }
  .origin-price {
    color: #f1f1f1;
    padding-left: 5px;
    font-size: 20px;
    text-decoration: line-through;
    font-weight: 100;
  }
  .price {
    flex-direction: row;
    align-items: flex-end;
    &-y {
      font-size: 24px;
      color: #fff;
      font-weight: 100;
    }
    &-val {
      color: #fff;
      font-size: 32px;
    }
  }

  .btn-del{
    font-size: 28px;
    color: #FFFFFF;
  }

  .textarea {
    font-size: 28px;
    line-height: 32px;
    color: $color;
    background-color: #f5f5f5;
    padding: 20px;
  }
</style>
<script>

import {WxcLoading, WxcPopup} from 'weex-ui'
let api = require('../include/api')
let Deferred = require('Deferred')
let dom = weex.requireModule('dom')
let urlPath = require('../include/url-path')
let navigator = require('../include/xnavigator')
let grouping = require('../include/grouping')
let modal = weex.requireModule('modal')
let paddingValue = [0, 12, 40]
let config = require('../include/app-config')
let DEFAULT_ITEM_SEARCH_PARAM = {
  page: 1,
  pageSize: 10,
  recommend: true
}
module.exports = {
  mixins: [
    require('../mixin/page-refresh'),
    require('../mixin/page-scrolltop'),
    require('../mixin/page-loading-more')
  ],
  components: {
    'page-notice': require('../components/page-notice.vue'),
    'navbar': require('../components/navbar.vue'),
    WxcLoading,
    WxcPopup
  },
  props: {
    height: {default: 0},
    back: {default: true},
    recommend: {default: ''},
    title: {default: null}
  },
  data () {
    return {
      userItemSelectionList: [],
      refreshing: false,
      refreshIndicatorScale: 0.2,
      sorryIcon: 'images/aiya.png',
      loadingShow: false,
      dialogShow: false,
      itemWidth: 750,
      shareBarPopupShow: false,
      column: 3,
      content: '',
      dialogContent: '',
      saveDoing: false,
      createResultDialogShow: false,
      hasNext: true,
      searchParam: {},
      iosShow: false,
      lxkAvatar: urlPath.assets('images/logo_la_t_200.png?v=2'),
      containerStyle: {},
      currentUserItemSelection: null
    }
  },
  created () {
    if (this.height) {
      this.containerStyle.height = this.height
    }
    this.itemWidth = (750 - paddingValue[this.column - 1]) / this.column
    this.sorryIcon = urlPath.assets(this.sorryIcon)
    Object.assign(this.searchParam, DEFAULT_ITEM_SEARCH_PARAM)
    config.bindConfig(this)
    Deferred.when(this.loadData(), this.search()).always(() => {
    })
  },
  methods: {
    loadData () {

    },
    shareBarPopupOverlayClick() {
      this.shareBarPopupShow = false
    },
    grouping: grouping,
    resetSearchParam () {
      Object.assign(this.searchParam, DEFAULT_ITEM_SEARCH_PARAM)
      this.hasNext = true
    },
    search (append) {
      return api.userItemSelection.recommendSearch(this.searchParam).done(rs => {
        setTimeout(() => {
          let data = rs.data
          if (append) {
            this.userItemSelectionList = this.userItemSelectionList.concat(data.results)
          } else {
            this.userItemSelectionList = data.results
          }
          this.hasNext = data.hasNext
        }, 200)
      })
    },
    getShareContent (content) {
      if (content) {
        content += '\n----------------\n'
      }
      content += '长按图片识别二维码，复制淘口令打开手机淘宝，领券购买！'
      return content
    },
    onXRefresh (event) {
      this.resetSearchParam()
      this.onRefresh(event, Deferred.when(this.search()))
    },
    onLoadingMore (event) {
      this.loadingMore = true
      this.searchParam.page = this.searchParam.page + 1
      this.search(true).done(() => {
        this.loadingMore = false
      })
    },
    gotoTop () {
      dom.scrollToElement(this.$refs.top)
    },
    onPageScroll (event) {
      this.onPageScrollForScrollTop(event)
    },
    commissionItemClick (item) {
      navigator.push('commission-item.js?id=' + item.id)
    },
    showShare (userItemSelection) {
      this.shareBarPopupShow = true
      this.currentUserItemSelection = userItemSelection
    },
    copyShareText () {
      let shareText = this.getShareContent(this.currentUserItemSelection.content)
      let clipboard = weex.requireModule('clipboard')
      clipboard.setString(shareText)
      modal.toast({message: '文案已复制到剪贴板', duration: 0.5})
      return shareText
    },
    share (to) {
      let weixinApi = weex.requireModule('weixinApi')
      let shareText = this.copyShareText(this.currentUserItemSelection)
      this.loadingShow = true
      api.userItemSelection.share({id: this.currentUserItemSelection.id}).done(rs => {
        let data = rs.data
        let images = this.currentUserItemSelection.itemList.map(o => api.url.commissionItem.sharePic({id: o.id, userId: data.userId, t: new Date().getTime()}))
        switch (to) {
          case 'img' :
            let album = weex.requireModule('album')
            this.loadingShown = true
            for (var k in images) {
              album.saveUrl(images[k], () => {
                this.loadingShow = false
                this.closeShareImgPanel()
              })
            }
            modal.toast({message: '保存成功', duration: 0.5})
            break
          case 'pyq':
            weixinApi.sendTimeline({
              images: images,
              text: shareText
            }, flag => {
              if (!flag) {
                modal.alert({message: '您还没有安装微信，无法分享，请先安装微信！'})
              }
            })
            break
          case 'wxhy':
            weixinApi.sendSession({
              images: images
            }, flag => {
              if (!flag) {
                modal.alert({message: '分享失败，请重试，如果您还没有安装微信，请先安装微信！'})
              }
            })
            break
        }
        this.loadingShow = false
      })
    }
  }
}
</script>
